package com.heima.dao;

import java.io.Serializable;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.List;

import javax.annotation.Resource;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Projections;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

import com.heima.daoInterface.IBaseDao;
import com.heima.tools.PageBean;

public class BaseDaoImpl<T> extends HibernateDaoSupport implements IBaseDao<T> {
	protected Class clazz;
	@Resource
	public void setSF(SessionFactory sessionFactory){
		super.setSessionFactory(sessionFactory);
	}
	public BaseDaoImpl(){
		Type type = ((ParameterizedType)this.getClass().getGenericSuperclass()).getActualTypeArguments()[0];
		clazz = (Class)type;
	}
	@Override
	public void save(T entity) {
		getHibernateTemplate().save(entity);
	}

	@Override
	public void update(T entity) {
		getHibernateTemplate().update(entity);
	}

	@Override
	public void delete(T entity) {
		getHibernateTemplate().delete(entity);
	}

	@Override
	public void executeByNamedQuery(String query, Object... args) {
		Session session = this.getSession();
		Query namedQuery = session.getNamedQuery(query);
		if(args != null && args.length != 0){
			int i =0;
			for (Object object : args) {
				namedQuery.setParameter(i++, object);
			}
			namedQuery.executeUpdate();
		}
	}

	@Override
	public T get(Serializable id) {
		return (T) getHibernateTemplate().get(clazz, id);
	}

	@Override
	public T findByNamedQuery(String query, Object... args) {
		List<T> list = getHibernateTemplate().findByNamedQuery(query, args);
		if (list != null && list.size()!=0) {
			return list.get(0);
		}
		return null;
	}

	@Override
	public List<T> findAll() {
		String query="from "+clazz.getSimpleName();
		return getHibernateTemplate().find(query);
	}

	@Override
	public List<T> findByCriteria(DetachedCriteria criteria) {
		return getHibernateTemplate().findByCriteria(criteria);
	}

	@Override
	public void pageBeanQuery(PageBean pageBean) {
		int currentPage = pageBean.getCurrentPage();
		DetachedCriteria criteria = pageBean.getCriteria();
		int pageSize = pageBean.getPageSize();
		DetachedCriteria rows = criteria.setProjection(Projections.rowCount());
		List list = getHibernateTemplate().findByCriteria(criteria);
		if (list != null && list.size() != 0) {
			Long lon = (Long) list.get(0);
			pageBean.setTotal(lon.intValue());
		}
		criteria.setProjection(null);
		criteria.setResultTransformer(DetachedCriteria.ROOT_ENTITY);
		List list2 = getHibernateTemplate().findByCriteria(criteria, (currentPage-1), pageSize);
		pageBean.setRows(list2);
	}
	
}
